package com.htjc.uep.center.commons.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.htjc.cht.api.util.AESCoder;
import com.htjc.cht.api.util.DigitalSignTool;

public class SignUtil {
	protected Log logger = LogFactory.getLog(getClass());
	private DigitalSignTool signerTool = null;
	private DigitalSignTool checkSignerTool = null;
	private AESCoder aesCoder = null;
	
	private static SignUtil signUtil = null;
//	public SignUtil() {
//		try {
//			logger.info(SignUtil.class.getName()+":"+SignUtil.class.getResource("cer/"));
//			logger.info(SignUtil.class.getName()+":"+SignUtil.class.getResource("cer/").getPath());
//			String path = java.net.URLDecoder.decode(SignUtil.class.getResource("cer/").getPath(), "utf-8");// 证书路径
//			String pfx_file = path + "dzfp.pfx"; // 商户证书路径
//			String keyStorePassword = "000000";// 商户证书库密码
//			String keyPassword = "000000";// 商户证书库私钥保护密码
//			String rootCertificatePath = path + "dzfp.pem";
//			signerTool = DigitalSignTool.getSigner(pfx_file, keyStorePassword,keyPassword); // 签名工具实例
//			checkSignerTool = DigitalSignTool.getVerifier(rootCertificatePath);
//		} catch (Exception e) {
//			throw new RuntimeException("网关证书服务异常，请联系管理员",e);
//		}
//	}
	
	/*String  path = Thread.currentThread().getContextClassLoader().getResource("").getPath().replace("%20", " ")
			 + File.separator + "clubID.txt";
			fileInputStream = new FileInputStream(new File(path));
			inputStream = new InputStreamReader(fileInputStream,"utf-8");*/
	
	private SignUtil() {
		try {
//			logger.info(SignUtil.class.getName()+":"+SignUtil.class.getResource("cer/"));
//			logger.info(SignUtil.class.getName()+":"+SignUtil.class.getResource("cer/").getPath());
			String path = java.net.URLDecoder.decode(System.getProperty("user.dir"), "utf-8");// 证书路径
			String pfx_file = path + "/src/main/resources/sign/dzfp.pfx"; // 商户证书路径
			String keyStorePassword = "000000";// 商户证书库密码
			String keyPassword = "000000";// 商户证书库私钥保护密码
			String rootCertificatePath = path + "/src/main/resources/sign/dzfp.pem";
			signerTool = DigitalSignTool.getSigner(pfx_file, keyStorePassword,keyPassword); // 签名工具实例
			checkSignerTool = DigitalSignTool.getVerifier(rootCertificatePath);
			aesCoder = AESCoder.getInstance();
		} catch (Exception e) {
			throw new RuntimeException("网关证书服务异常，请联系管理员",e);
		}
	}
	
	public static SignUtil getInstance(){
		if (signUtil == null) {
			signUtil = new SignUtil();
		}
		return signUtil;
	}
	
	/**
	*  数据签名（加签）
	*  @param orginalData待签名数据
	*  @return 成功返回：签名数据；失败返回：null
	*/
	public String sign(String orginalData) {
		String signData = null;
		try {
			signData = signerTool.sign(orginalData.getBytes());
		}  catch (Exception e) {
			logger.error("报文签名失败"+e.getMessage(),e);
		}
		return signData;

	}
	
	/**
	 * 数据验证（验签）
	 * @Description : 数据验证  
	 * @param requestXml
	 * @return boolean true 验签通过  false 未通过
	 * @auther:YAOYUAN
	 */
	public boolean verifySign(final String sign, String param) {
		
		try {
			checkSignerTool.verify(sign, param.getBytes(), null);
			return true;
//			if (requestXml.contains("<SUMMARY>")
//					&& requestXml.contains("</SUMMARY>")) {
//				final String summary = requestXml.split("<SUMMARY>")[1].split("</SUMMARY>")[0];
//				final String request = requestXml.split("<SUMMARY>")[0]+ requestXml.split("</SUMMARY>")[1];
//				// 验签
//				checkSignerTool.verify(summary, request.getBytes(), null);
//				return true;
//			} else {
//				return false;
////				if(InvoiceContant.ELE_INVOICE_SYSERR.equals(requestXml.split("<RETURN_CODE>")[1].split("</RETURN_CODE>"))){
////					return true;
////				}else{
////					return false;
////				}
//			}
		} catch (Exception e) {
			logger.error("验签报文失败"+e.getMessage(),e);
			return false;
		}
	}
	
	public String aesDecrypt(String str) throws Exception {
		return aesCoder.decrypt(str);
	}
	
	public String aesEncrypt(String str) throws Exception {
		return aesCoder.encrypt(str);
	}
	
	/**
	 * 加解密组装javaBean
	 * @param obj
	 * @param isEcrypt 0加密 1解密
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public <T> T  getDEBean(Object obj, String isEcrypt) throws Exception {
		
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		
		for (Field field : fields) {
			
			field.setAccessible(false);
			
			String getMethodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
			String setMethodName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
			
			Method getMethod = clazz.getMethod(getMethodName);
			
			String strSign = (String) getMethod.invoke(obj);
			
			String str = "";
			if ("0".equals(isEcrypt)) {
				if ("sign".equals(field.getName())){
					//do nothing
				} else {
					str = aesEncrypt(strSign);
				}
			} else if ("1".equals(isEcrypt)){
				if ("sign".equals(field.getName())){
					str = strSign;
				} else {
					str = aesDecrypt(strSign);
				}
			} else {
				throw new RuntimeException("加解密类型错误");
			}
			
			Method setMethod = clazz.getMethod(setMethodName, String.class);
			setMethod.invoke(obj, str);
		}
		return (T) obj;
	}
}





































